<?php

App::uses('AppController', 'Controller');
App::import('Vendor', 'recaptchalib');
App::import('Vendor', 'captcha/securimage');

/**
 * Roses Controller
 *
 * @property Rose $Rose
 */
class RosesController extends AppController {

    var $layout = 'roses';
    public $helpers = array('Gravatar', 'Recaptcha');

    public function beforeFilter() {
        #parent::beforeFilter();
        #allow not login
        $this->Auth->allow(array('index', 'display', 'commentPost', 'commentProduct', 'addToCart', 'showCart', 'updateCart',
            're	freshCart', 'deleteCartItem', 'paymentInfo', 'showCaptcha'));

        $this->loadModel('Category');
        $this->loadModel('Product');
        $this->loadModel('Post');
        $this->Category->recursive = -1;
        $infoCategory = $this->Category->find('first', array('conditions' => array('Category.type' => Category::information)));
        if ($infoCategory) {
            $infors = $this->Post->find('all', array('conditions' => array(	'category_id' => $infoCategory['Category']['id'],
																																					 	'Post.status' => Post::publish,
																																						'Post.schedule_public_date <=' => date("Y-m-d H:i:s"))));
            $this->set('infors', $infors);
        }

        $this->set('infoCategory', $infoCategory);
    }

    public function showCaptcha() {

        //$this->autoLayout = false; //a blank layout 
        $this->autoRender = false;
        //override variables set in the component - look in component for full list 
//        $this->captcha->image_bg_color = '#ffffff'; 
//        $this->captcha->line_color = '#cccccc'; 
//        $this->captcha->arc_line_colors = '#999999,#cccccc'; 
//        $this->captcha->code_length = 5; 
//        $this->captcha->font_size = 45; 
        
        $img = new Securimage();
        //$img->captcha_type    = Securimage::SI_;
        $img->code_length = 3;
        $img->background_directory = WWW_ROOT . 'img/backgrounds/';
        $this->set('captcha_data', $img->show()); //dynamically creates an image 
    }

    public function index() {
        $this->loadModel('Slider');

        $slider = $this->Slider->find('first');
        $this->set('slider', $slider);

        $this->Product->recursive = 1;
        $products = $this->Product->find('all', array('limit' => 3));
        $this->set('products', $products);

        $mainPost = $this->Post->find('first', array('order' => array('Post.created_at' => 'desc'),
            'conditions' => array('Post.type' => Post::news, 'Post.status' => Post::publish)));
        $this->set('mainPost', $mainPost);

        //get random posts
        $this->Post->recursive = -1;
        if ($mainPost) {
            $randPosts = $this->Post->find('all', array('order' => 'rand()', 'limit' => 2,
                'conditions' => array('Post.id NOT' => $mainPost['Post']['id'],
                    'Post.type' => Post::news)));
            $this->set('randPosts', $randPosts);
        }
    }

    public function display() {
        $path = func_get_args();
        $this->set('captcha_image_url', $this->webroot . 'securimage');
        $count = count($path);
        if (!$count) {
            $this->redirect('/');
        }

        $page = end($path);
        $this->Category->recursive = -1;
        $category = $this->Category->findBySlug($page);
        if (!empty($category)) {
            #in this case: category page
            #check categories path
            $realPath = $this->Category->getPath($category['Category']['id'], array('id', 'slug'), -1);
            foreach ($realPath as $i => $p) {
                if (!empty($path[$i])) {
                    if ($path[$i] != $p['Category']['slug']) {
                        $this->render('/Errors/error404');
                        return;
                    }
                } else {
                    $this->render('/Errors/error404');
                    return;
                }
            }

            $this->set('str_menu', $category['Category']['slug']);
            $this->set('category', $category);
            //choose template
            if ($category['Category']['type'] == Category::home) {
                //Call function to prepare data
                $this->index();
                $this->render('Index');
                return;
            } elseif ($category['Category']['type'] == Category::contact) {
                //Call function to prepare data
                $this->contact_template();
                $this->render('TemplateContact');
                return;
            } elseif ($category['Category']['type'] == Category::about) {
                //Call function to prepare data
                $this->about_template();
                $this->render('TemplateAbout');
                return;
            } elseif ($category['Category']['type'] == Category::products) {
                //Call function to prepare data
                $this->products_template();
                $this->render('TemplateProducts');
                return;
            } elseif ($category['Category']['type'] == Category::posts) {
                //Call function to prepare data
                $this->posts_template($category['Category']['id']);
                $this->render('TemplatePosts');
                return;
            } elseif ($category['Category']['type'] == Category::information) {
                //Call function to prepare data
                $this->information_template($category['Category']['id']);
                $this->render('TemplateInformation');
                return;
            }
        } else {
            #in this case: detail post page
            $this->Post->recursive = 0;
            $post = $this->Post->find('first', array('conditions' => array('Post.slug' => $page,
                    'Post.status' => Post::publish)));
            if (!empty($post)) {
                $this->set('str_menu', $post['Category']['slug']);
                $this->post_detail_template($post['Category']['slug'], $post['Post']['id']);
                $this->set('post', $post);
                $this->set('title_for_layout', $post['Post']['title']);
                $this->render('TemplatePostDetail');
                return;
            } else {
                $product = $this->Product->find('first', array('conditions' => array('Product.slug' => $page,
                        'Product.status' => Product::active)));
                if (!empty($product)) {
                    $this->set('str_menu', $page);
                    $this->product_detail_template($product['Product']['id'], $page);
                    $this->set('product', $product);
                    $this->render('TemplateProductDetail');
                    return;
                } else {
                    $this->render('/Errors/error404');
                    return;
                }
            }
            #Check detail path
        }
        #$this->render(implode('/', $path));
    }

    /**
     * Contact Template
     * Dev: Hung Nguyen
     */
    function contact_template() {
        $this->loadModel('Comment');
        $products = $this->Product->getFeatureProductSide();
        $this->set('products', $products);

        # captcha secuimage
        $securimage = new Securimage();
	      if ($this->request->is('post')) {			
  	      if ($securimage->check($this->data['Captcha']['captcha_code']) == false) {
            //the code was incorrect - display an error message to user 
            $this->set('error_captcha', __('Mã xác nhận không chính xác')); //set error msg 
						$this->Session->setFlash(__('Vui lòng điền đầy đủ thông tin yêu cầu'), 'default', array(), 'bad');
	        }else{
	          $this->Comment->create();
	          $this->request->data['Comment']['status'] = Comment::active;
	          $this->request->data['Comment']['type'] = Comment::contact;
	          $this->request->data['Comment']['created_at'] = date("Y-m-d H:i:s");
	          if ($this->Comment->save($this->request->data)) {
	              $this->set('id', $this->Comment->id);
	          } else {
	              $this->Session->setFlash(__('Vui lòng điền đầy đủ thông tin yêu cầu'), 'default', array(), 'bad');
	          }
					}
	      }
    }

    /**
     * Post Template
     * Dev: Hung Nguyen
     */
    function posts_template($categoryId) {
        //get products
        $products = $this->Product->getFeatureProductSide();
        $this->set('products', $products);

        //get posts
        $this->paginate = array('limit' => 5,
            'order' => array('Post.created_at' => 'desc'),
            'conditions' => array('Post.category_id' => $categoryId, 
																	'Post.status' => Post::publish,
																	'Post.schedule_public_date <=' => date("Y-m-d H:i:s")));
        $this->Post->recursive = -1;
        $this->set('posts', $this->paginate('Post'));
    }

    /**
     * Information Template
     * Dev: Hung Nguyen
     */
    function information_template($categoryId) {
        //get products
        $products = $this->Product->getFeatureProductSide();
        $this->set('products', $products);

        //get posts
        $this->paginate = array('order' => array('Post.created_at' => 'desc'),
            										'conditions' => array('Post.category_id' => $categoryId,
																											'Post.status' => Post::publish,
																											'Post.schedule_public_date <=' => date("Y-m-d H:i:s")));
        $this->Post->recursive = -1;
        $this->set('posts', $this->paginate('Post'));
    }

    /**
     * Post Detail Template
     * Dev: Hung Nguyen
     */
    function post_detail_template($slug = null, $id) {
        //get products
        $products = $this->Product->getFeatureProductSide();
        $this->set('products', $products);
        //get comments of post	
        $this->loadModel('Comment');
        $this->Comment->recursive = 0;
        $comments = $this->Comment->find('all', array('conditions' => array('owner_id' => $id,
                'owner_model' => 'Post',
                'Comment.status' => array(Comment::active, Comment::allowShow))));
        $this->set('comments', $comments);
        
        
        if ($this->request->is('post')) {
		
            # captcha secuimage
            $securimage = new Securimage();
            if ($securimage->check($this->data['Captcha']['captcha_code']) == false) {
                //the code was incorrect - display an error message to user 
                $this->set('error_captcha', __('Mã xác nhận không chính xác')); //set error msg 
								$this->Session->setFlash(__('Vui lòng điền đầy đủ thông tin yêu cầu'), 'default', array(), 'bad');
            }else{
		          $post = $this->Post->findById($id);
		          if ($post) {
		              $this->Comment->create();
		              $this->request->data['Comment']['status'] = Comment::active;
		              $this->request->data['Comment']['type'] = Comment::comment;
		              $this->request->data['Comment']['owner_model'] = 'Post';
		              $this->request->data['Comment']['created_at'] = date("Y-m-d H:i:s");
		              if ($this->Comment->save($this->request->data)) {
		                  $this->set('id', $this->Comment->id);
		                  $this->redirect($this->request->data['Comment']['callback']);
		              } else {
		                  $this->Session->setFlash(__('Vui lòng điền đầy đủ thông tin yêu cầu'), 'default', array(), 'bad');
		              }
		          } else {
		              $this->Session->setFlash(__('Thông tin không phù hợp, Vui lòng thử lại'), 'default', array(), 'bad');
		          }
					}
        }
    }

    /**
     * About Template
     * Dev: Hung Nguyen
     */
    function about_template() {
        $this->Category->recursive = -1;
        $this->Post->recursive = -1;
        $aboutCategory = $this->Category->find('first', array('conditions' => array('Category.type' => Category::about)));
        $about = $this->Post->find('first', array('conditions' => array('category_id' => $aboutCategory['Category']['id'])));
        $this->set('about', $about);

        $products = $this->Product->getFeatureProductSide();
        $this->set('products', $products);
    }

    /**
     * Product Template
     * Dev: Hung Nguyen
     */
    function products_template($slug = null) {
        $products = $this->Product->find('all', array('order' => 'created_at desc',
            'conditions' => array('Product.status' => Product::active)));
        $posts = $this->Post->getPostSide();

        $this->set('posts', $posts);
        $this->set('products', $products);
    }

    /**
     * product_detail_template
     * Dev: Hung Nguyen
     */
    function product_detail_template($id, $slug = null) {
        $posts = $this->Post->getPostSide();
        $this->set('posts', $posts);

        //get comments
        $this->loadModel('Comment');
        $this->Comment->recursive = 0;
        $comments = $this->Comment->find('all', array('conditions' => array('owner_id' => $id,
                'owner_model' => 'Product',
                'Comment.status' => array(Comment::active, Comment::allowShow))));
        $this->set('comments', $comments);
				if ($this->request->is('post')) {
		
            # captcha secuimage
            $securimage = new Securimage();
            if ($securimage->check($this->data['Captcha']['captcha_code']) == false) {
                //the code was incorrect - display an error message to user 
                $this->set('error_captcha', __('Mã xác nhận không chính xác')); //set error msg 
								$this->Session->setFlash(__('Vui lòng điền đầy đủ thông tin yêu cầu'), 'default', array(), 'bad');
            }else{
		        	$post = $this->Post->findById($id);
		          $product = $this->Product->findById($id);
		          if ($product) {
		              $this->Comment->create();
		              $this->request->data['Comment']['status'] = Comment::active;
		              $this->request->data['Comment']['type'] = Comment::comment;
		              $this->request->data['Comment']['owner_model'] = 'Product';
		              $this->request->data['Comment']['created_at'] = date("Y-m-d H:i:s");
		              if ($this->Comment->save($this->request->data)) {
		                  $this->set('id', $this->Comment->id);
		                  $this->redirect($this->request->data['Comment']['callback']);
		              } else {
		                  $this->Session->setFlash(__('Vui lòng điền đầy đủ thông tin yêu cầu'), 'default', array(), 'bad');
		              }
		          } else {
		              $this->Session->setFlash(__('Thông tin không phù hợp, Vui lòng thử lại'), 'default', array(), 'bad');
		          }
					}
				}
    }

    /**
     * Comment Post
     * Dev: Hung Nguyen
     */
    function commentPost($id = null) {
#        $this->loadModel('Comment');
#        if ($this->request->is('post')) {

#            # Get captcha
#            #			$privatekey = Configure::read('Recaptcha.Private');
#            #		  $resp = recaptcha_check_answer ($privatekey,
#            #                                $_SERVER["REMOTE_ADDR"],
#            #                                $_POST["recaptcha_challenge_field"],
#            #                                $_POST["recaptcha_response_field"]);
#            #		  if (!$resp->is_valid) {
#            #				// What happens when the CAPTCHA was entered incorrectly
#            #					$this->Session->setFlash(__('Ma Xac Nhan Khong Dung'), 'default', array(), 'bad');
#            #				$this->redirect($this->request->data['Comment']['callback']);
#            #		  }else{
#            #		  }
#            # captcha secuimage
#            $securimage = new Securimage();

#            if ($securimage->check($this->data['Captcha']['captcha_code']) == false) {
#                //the code was incorrect - display an error message to user 
#                $this->set('error_captcha', 'sai'); //set error msg 
#                //$this->render($this->request->data['Comment']['callback']); //reload page 
#            } else {
#                //the code was correct - display a success message to user 
#                $this->set('success_captcha', 'dung'); //set success msg 
#                //$this->render(); //reload page 
#                //after testing is complete, you would process the other form data here and save it
#            }

#            $post = $this->Post->findById($id);
#            if ($post) {
#                $this->Comment->create();
#                $this->request->data['Comment']['status'] = Comment::active;
#                $this->request->data['Comment']['type'] = Comment::comment;
#                $this->request->data['Comment']['owner_model'] = 'Post';
#                $this->request->data['Comment']['created_at'] = date("Y-m-d H:i:s");
#                if ($this->Comment->save($this->request->data)) {
#                    $this->set('id', $this->Comment->id);
#                    $this->redirect($this->request->data['Comment']['callback']);
#                } else {
#                    $this->Session->setFlash(__('Vui lòng điền đầy đủ thông tin yêu cầu'), 'default', array(), 'bad');
#                }
#            } else {
#                $this->Session->setFlash(__('Thông tin không phù hợp, Vui lòng thử lại'), 'default', array(), 'bad');
#            }
#        }
#        
    }

    /**
     * Comment Product
     * Dev: Hung Nguyen
     */
    function commentProduct($id = null) {
#        $this->loadModel('Comment');
#        if ($this->request->is('post')) {
#            $product = $this->Product->findById($id);
#            if ($product) {
#                $this->Comment->create();
#                $this->request->data['Comment']['status'] = Comment::active;
#                $this->request->data['Comment']['type'] = Comment::comment;
#                $this->request->data['Comment']['owner_model'] = 'Product';
#                $this->request->data['Comment']['created_at'] = date("Y-m-d H:i:s");
#                if ($this->Comment->save($this->request->data)) {
#                    $this->set('id', $this->Comment->id);
#                } else {
#                    $this->Session->setFlash(__('Vui lòng điền đầy đủ thông tin yêu cầu'), 'default', array(), 'bad');
#                }
#            } else {
#                $this->Session->setFlash(__('Thông tin không phù hợp, Vui lòng thử lại'), 'default', array(), 'bad');
#            }
#        }
#        $this->redirect($this->request->data['Comment']['callback']);
    }

    /**
     * Add To Cart
     * Dev: Hung Nguyen
     */
    function addToCart($id = null) {
        $this->autoRender = false;
        if (!$this->request->is('ajax')) {
            return "ERROR";
        }
        if ($this->request->is('post')) {
            $product = $this->Product->findById($id);
            //Get Variant
            $this->loadModel('Variant');
            $master = $this->Variant->find('first', array('conditions' => array('product_id' => $id, 'is_master' => true)));
            if ($product && $master) {
                $this->Product->rescusive = -1;

                //----------------------Implement Cart----------------------------------
                $total = 0;
                $items = array();
                if ($this->Session->check('Cart.items')) {
                    $items = $this->Session->read('Cart.items');
                }

                //update items
                $updateFlag = false;
                foreach ($items as $i => $it) {
                    if ($it['id'] == $id) {
                        $updateFlag = true;
                        $items[$i]['quantity'] = $it['quantity'] + $this->request->data['Cart']['quantity'];
                    }
                    $total += $items[$i]['quantity'];
                }

                if ($updateFlag == false) {
                    $item = array('id' => $product['Product']['id'],
                        'name' => $product['Product']['name'],
                        'price' => $master['Variant']['price'],
                        'photo' => $master['Image']['0'],
                        'quantity' => $this->request->data['Cart']['quantity']);
                    array_push($items, $item);
                    $total += $item['quantity'];
                }
                $this->Session->write('Cart.items', $items);
                $this->Session->write('Cart.countProduct', $total);

                //----------------------End Implement Cart------------------------------


                $this->render('/Elements/Frontend/cart', 'ajax');
            }
        }
        return "ERROR";
    }

    /**
     * refreshCart
     * Dev: Hung Nguyen
     */
    public function refreshCart() {
        $this->render('/Elements/Frontend/cart', 'ajax');
    }

    /**
     * ShowCart
     * Dev: Hung Nguyen
     */
    public function showCart() {
        
    }

    /**
     * deleteCartItem
     * Dev: Hung Nguyen
     */
    public function deleteCartItem($id = null) {
        if (!$this->request->is('ajax')) {
            return "ERROR";
        }
        if ($this->request->is('post')) {
            $product = $this->Product->findById($id);
            if ($product) {
                $quantity = 0;
                $total = 0;
                $items = array();
                if ($this->Session->check('Cart.items')) {
                    $items = $this->Session->read('Cart.items');
                }

                if ($this->Session->check('Cart.countProduct')) {
                    $total = $this->Session->read('Cart.countProduct');
                }

                //update items
                foreach ($items as $i => $it) {
                    if ($it['id'] == $id) {
                        $quantity = $items[$i]['quantity'];
                        unset($items[$i]);
                    }
                }

                $this->Session->write('Cart.items', $items);
                $this->Session->write('Cart.countProduct', $total - $quantity);
                $this->render('/Elements/Frontend/show_cart', 'ajax');
            }
        }
        return "ERROR";
    }

    /**
     * updateCart
     * Dev: Hung Nguyen
     */
    public function updateCart($id) {
        if (!$this->request->is('ajax')) {
            return "ERROR";
        }
        if ($this->request->is('post')) {
            $product = $this->Product->findById($id);
            if ($product) {
                $total = 0;
                $items = array();
                if ($this->Session->check('Cart.items')) {
                    $items = $this->Session->read('Cart.items');
                }

                //update items
                foreach ($items as $i => $it) {
                    if ($it['id'] == $id) {
                        $items[$i]['quantity'] = $this->request->data['Cart']['quantity'];
                    }
                    $total += $items[$i]['quantity'];
                }

                $this->Session->write('Cart.items', $items);
                $this->Session->write('Cart.countProduct', $total);

                $this->render('/Elements/Frontend/show_cart', 'ajax');
            }
        }
        return "ERROR";
    }

    /**
     * payment_info
     * Dev: Hung Nguyen
     */
    public function paymentInfo() {
        $this->loadModel('City');
        $cities = $this->City->find('list');
        $this->set('cities', $cities);
        echo "XxxxxxxxxxxxxxxX";
    }

}
